﻿#include "ThreadShowDiscsOnWin.h"
#include <StdClassFun.h>

// 获取驱动信息
void ThreadShowDiscsOnWin::getDiscInfo(QVector<char*>& chars) {
	static ULARGE_INTEGER nFreeBytesAvailable{ }; //可用空间
	static ULARGE_INTEGER nTotalNumberOfBytes{ }; //总空间
	static ULARGE_INTEGER nTotalNumberOfFreeBytes{ }; //剩余空间
	if( runStats( ) )
		return;
	discInfo.clear( );
	for( auto& distName : chars ) {
		// 获取信息
		if( GetDiskFreeSpaceExA(distName, &nFreeBytesAvailable, &nTotalNumberOfBytes, &nTotalNumberOfFreeBytes) ) {
			QString objName(distName);
			QString targetStr = objName.replace("/", "").replace(":", "").replace("\\", "");
			if( runStats( ) )
				return;
			// 获取内存
			QHash<QString, ULARGE_INTEGER> buff = discInfo.value(targetStr);
			// 获取内存
			buff.insert(getFreeBytesAvailableKey( ), nFreeBytesAvailable);
			buff.insert(getTotalNumberOfBytesKey( ), nTotalNumberOfBytes);
			buff.insert(getTotalNumberOfFreeBytes( ), nTotalNumberOfFreeBytes);
			discInfo.insert(targetStr, buff);
		}
	}
}

int ThreadShowDiscsOnWin::runStats(int status) {
	QMutexLocker locker(statsMutex);
	static int _status = 0;
	if( status )
		return _status;
	_status = status;
	return _status;
}

// 解析
ThreadShowDiscsOnWin::ThreadShowDiscsOnWin(QObject* parent) : QThread{ parent } {
	buff = new char[maxBuffLen];
	statsMutex = new QMutex;
}

ThreadShowDiscsOnWin::~ThreadShowDiscsOnWin( ) {
	while( isRunning( ) ) {
		runStats(1);
		wait( );
	}
	quit( );
	if( buff )
		delete buff;
	if( statsMutex )
		delete statsMutex;
}

void ThreadShowDiscsOnWin::run( ) {
	// 磁盘名称缓存
	QVector<char*> chars;
	memset(buff, 0, maxBuffLen);
	GetLogicalDriveStringsA(maxBuffLen, buff);
	char* pDrives = buff;
	while( *pDrives != 0 ) {
		chars.append(pDrives);
		pDrives += strlen(pDrives) + 1;
	}
	getDiscInfo(chars);
	// 结束信息
	emit sendDiscInfo(&discInfo);
}
